import {Message} from '../../../db/models/message'
import {sendSuccess, sendError} from "../../utils/responseHandler";
import sequelize from "../../../db";
import {QueryTypes} from "sequelize";

export default async function handler(req, res) {
    if (req.method === 'POST') {
        try {
            const {workId, userId1, userId2} = req.body;

            const query = `SELECT * FROM db_messages 
                       WHERE work_id = :workId AND 
                             ((user_id = :userId1 AND target_user_id = :userId2) OR (user_id = :userId2 AND target_user_id = :userId1))
                       ORDER BY timestamp`;
            const messageData = await sequelize.query(query, {
                replacements: {workId: workId, userId1: userId1, userId2: userId2},
                type: QueryTypes.SELECT
            });
            sendSuccess(res, messageData);
        } catch (error) {
            console.error('获取失败:', error);
            sendError(res, '获取失败', 500);
        }
    } else {
        res.setHeader('Allow', ['GET', 'POST']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
    }
}
